package com.xlr.excel.task;

import com.xlr.excel.entity.SourseVehicle;
import com.xlr.excel.queue.QueueHander;
import com.xlr.excel.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: xlr
 * @Date: Created in 下午7:54 2019/3/3
 */
@Slf4j
public class QueueTaskThread implements Runnable {

    QueueHander queueHander;

    public volatile static int size = 999;

    Executor executor = Executors.newFixedThreadPool(100);

    public QueueTaskThread( QueueHander queueHander ){
        this.queueHander =queueHander;
    }
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

    List<SourseVehicle> list = new ArrayList <>(  );
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        log.warn( "time:{}" ,new Date(  ));
        while (true){
            SourseVehicle task = queueHander.getTask();
            list.add( task );
            if(list.size()>size){
                List<SourseVehicle> list2 = new ArrayList <>(  );
                list2.addAll( list );
                executor.execute( new QueueCoreThread( list2 ) );
                list.clear();
            }
        }
    }

    /**
     * 20分钟内只能执行一次
     */
    private void timeTask(){
        try {
            Thread.sleep(1000*60*15);
            new QueueCoreThread( list );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static int getSize() {
        return size;
    }

    public static void setSize(int size) {
        QueueTaskThread.size = size;
    }
}
